package com.zfzs.post.modules.agent.service.impl;

import com.alibaba.fastjson.JSON;
import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.model.dto.QueryFindAgentInfoPageDTO;
import com.zfzs.post.model.dto.UpdateAgentInfoDTO;
import com.zfzs.post.model.vo.QueryAddAgentListVO;
import com.zfzs.post.modules.agent.domain.Agent;
import com.zfzs.post.modules.agent.domain.AgentInfo;
import com.zfzs.post.modules.agent.repository.AgentRepository;
import com.zfzs.post.modules.agent.service.AgentInfoService;
import com.zfzs.post.modules.agent.service.AgentService;
import com.zfzs.post.modules.agent.service.dto.AgentQueryCriteria;
import com.zfzs.post.modules.agent.service.mapper.AgentMapper;
import com.zfzs.post.modules.agent.service.mybatis.IAgentService;
import com.zfzs.post.modules.backstage.domain.UserInfo;
import com.zfzs.post.modules.backstage.service.BackStageUserService;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.utils.PageUtil;
import com.zfzs.post.utils.QueryHelp;
import com.zfzs.post.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 代理商基础信息
 *
 * @author ck
 * @date 2019-08-07
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AgentInfosServiceImpl implements AgentService {

    @Autowired
    private AgentRepository agentRepository;

    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private AgentMapper agentMapper;

    @Autowired
    private BackStageUserService backStageUserService;

    @Autowired
    private IAgentService iAgentService;

    @Override
    public Object queryAll(AgentQueryCriteria criteria, Pageable pageable) {
        Page<Agent> page = agentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(agentMapper::toDto));
    }

    @Override
    public Object queryAll(AgentQueryCriteria criteria) {
        return agentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
    }

    @Override
    public Agent findById(Long id) {
        Optional<Agent> agent = agentRepository.findById(id);
        if (!agent.isPresent()) {
            return null;
        }
        return agent.get();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent create(Agent resources) {
        //生成iD
        // String id = StringUtils.getRandomNumberString(8);
        //resources.setId(Long.valueOf(id));
        resources.setDelFlag(false);
        resources.setCreateDate(new Timestamp(System.currentTimeMillis()));
        resources.setIsEffective(0);
        resources.setIsEnabled(false);
        resources.setStatus(0L);
        resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
        return agentRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Agent resources) {
        resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        Optional<Agent> optionalAgent = agentRepository.findById(resources.getId());
        ValidationUtil.isNull(optionalAgent, "Agent", "id", resources.getId());
        Agent agent = optionalAgent.get();
        agent.copy(resources);
        agentRepository.save(agent);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        agentRepository.deleteById(id);
    }

    @Override
    public Agent findByPhoneAndChannelId(String phone, Long channelId) {
        //查询渠道是否存在
        UserInfo user = backStageUserService.findById(channelId);
        if (user == null) {
            throw new BadRequestException("没有查询到所属逇渠道信息");
        }
        Agent agent = agentRepository.findByPhoneAndChannelId(phone, channelId);
        return agent;
    }


    @Override
    public Agent findByNickName(String nickName) {
        AgentInfo info = agentInfoService.findByNickName(nickName);
        if (info != null) {
            Long id = info.getId();
            Agent agent = agentRepository.findByid(id);
            return agent;
        }
        return null;
    }

    @Override
    public List<Agent> findByPidId(Long id) {
        return agentRepository.findByPidId(id);
    }

    @Override
    public List<Agent> getAgentListByKeywords(String keywords, List<Long> ids) {
        return agentRepository.findByPhoneOrNickName(keywords, ids);
    }

    @Override
    public List<Agent> getAgentByIdsList(List<Long> ids) {
        return agentRepository.findByIds(ids);
    }

    @Override
    public Boolean isDirectly(Long id, Long pidId) {
        int count = agentRepository.countDirectly(id, pidId);
        if (count == 0) {
            return false;
        }else{
            return true;
        }
    }

    @Override
    public int queryCountByAgentIds(Long channelId, List<Long> ids, String startDate, String endDate) {
        return agentRepository.queryCountByAgentIds(channelId, ids, startDate, endDate);
    }

    @Override
    public List<QueryAddAgentListVO> queryAddAgentList(List<Long> ids, Long channelId, String startDate, String endDate) {
        List<Map<String, Object>> list = agentRepository.queryAddAgentList(ids, channelId, startDate, endDate);
        List<QueryAddAgentListVO> collect = list.stream()
                .map(e -> {
                    QueryAddAgentListVO agent = JSON.parseObject(JSON.toJSONString(e), QueryAddAgentListVO.class);
                    return agent;
                }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public JpaPageHelper queryAgentInfoPageList(QueryFindAgentInfoPageDTO criteria, Integer page, Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size);//借助计算起始位置
        // 计算数据总条数
        int total = iAgentService.findAgentInfoPageCount(criteria);
        List<Map<String, Object>> records = iAgentService.findAgentInfoPageList(criteria, pageRequest.getOffset(), pageRequest.getPageSize());
        JpaPageHelper jpaPage = new JpaPageHelper<>(records, page, size, total);
        // 转换分页数据
        jpaPage.setResult(records);
        return jpaPage;
    }

    @Override
    public Agent queryAgentTop(Long channelId) {
        return agentRepository.queryAgentTop(channelId);
    }
}